<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" :placeholder="$t('菜单名称')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-if="$store.getters.button.includes('system:menu:search')"  v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-if="$store.getters.button.includes('system:menu:add')"  class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      style="width: 100%;"
      element-loading-text="请稍后..."
      row-key="id"
      border
      fit
      highlight-current-row
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @sort-change="sortChange"
    >
      <el-table-column prop="title" label="标题" min-width="60" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" v-model="scope.row.name" style="width: 50%" size="small" placeholder="标题">
            {{ scope.row.name }}
          </el-input>
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路由地址" min-width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input v-if="scope.row.edit" v-model="scope.row.path" size="small" placeholder="路由地址">
            {{ scope.row.path }}
          </el-input>
          <span v-else>{{ scope.row.path }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="permission" label="按钮值" min-width="40" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.rval }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="序号" min-width="30">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.edit"
            v-model="scope.row.sort"
            size="small"
            controls-position="right"
            placeholder="序号"
            :min="0"
            style="width: 90px"
          />
          <span v-else>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" min-width="30" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-select v-if="scope.row.edit" v-model="scope.row.type" size="small" placeholder="请选择">
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
          </el-select>
          <span v-else>
            <el-tag v-if="scope.row.type===1" size="mini" type="success">菜单</el-tag>
            <el-tag v-else-if="scope.row.type===2" size="mini" type="warning">按钮</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')" class-name="status-col" min-width="30">
        <template slot-scope="{row}">
          <span v-if="row.status==0" style="color: limegreen;">启用</span>
          <span v-else style="color: red;">禁用</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="210px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button  v-if="$store.getters.button.includes('system:menu:edit')" type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="$store.getters.button.includes('system:menu:delete')" size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="98px" style="width: 360px; margin-left:10px;">
              <el-form-item :label="$t('父级菜单名称')" prop="menuname">
                <treeselect
                  v-model="temp.pid"
                  :normalizer="normalizer"
                  placeholder="请选择..."
                  :multiple="false"
                  :options="menuList"
                  :default-expand-level="1"
                  no-options-text="暂无数据"
                  @select="treeOnSelect"
                />
              </el-form-item>
              <el-form-item :label="$t('菜单名称')" prop="name">
                <el-input v-model="temp.name" />
              </el-form-item>
              <el-form-item :label="$t('meta标题')" prop="metaTitle">
                <el-input v-model="temp.metaTitle" />
              </el-form-item>
              <el-form-item :label="$t('路径')" prop="path">
                <el-input v-model="temp.path" />
              </el-form-item>
              
            </el-form>
          </el-col>
          <el-col :span="12" style="border-left: solid 1px #dcdfe6;">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="98px" style="width: 360px; margin-left:10px;">
              <el-form-item :label="$t('排序')" prop="sort">
                <el-input v-model.number="temp.sort" oninput="value=value.replace(/[^\d]/g,'')" maxlength="9" />
              </el-form-item>
              <el-form-item :label="$t('类型')">
                <el-select v-model="temp.type" placeholder="请选择">
                  <el-option
                    v-for="item in optiontype"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('按钮值')" prop="rval">
                <el-input v-model="temp.rval" />
              </el-form-item>
              <el-form-item :label="$t('状态')">
                <el-select v-model="temp.status" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getAuthMenu, getsave, getupdate, getdelByIdentify } from '@/api/menu'
import Treeselect from '@riophae/vue-treeselect'
import { jsonTree } from '@/utils/tree'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default{
  name: 'MenuTable',
  components: { Pagination, Treeselect },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      menuid: '',
      value: null,
      menuList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: ''
      },
      // 后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
      normalizer(node) {
        // 去掉children=[]的children属性
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      options: [{
        value: 0,
        label: '启用'
      }, {
        value: 1,
        label: '禁用'
      }],
      optiontype: [{
        value: 1,
        label: '菜单'
      }, {
        value: 2,
        label: '按钮'
      }],
      temp: {
        id: undefined,
        name: '',
        path: '',
        type: 1,
        sort: 0,
        pid: '0',
        status: 0,
        menuid: '',
        metaTitle: '',
        rval: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '菜单名不能为空', trigger: 'blur' }],
        metaTitle: [{ required: true, message: 'meta标题不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getAuthMenu().then(response => {
        this.list = jsonTree(response.data, {
          id: 'id',
          pid: 'pid',
          children: 'children'
        })
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getTreeMenuList() {
      getAuthMenu().then(response => {
        this.menuList = jsonTree(response.data, {
          id: 'id',
          pid: 'pid',
          children: 'children'
        })
        if (this.list !== undefined && this.list.length > 0) {
          this.value = []
          this.value.push(response.data[0].id)
        }
      })
    },
    // 获取节点选中的数据
    treeOnSelect(val) {
      this.menuid = val.pid
    },
    getNode(id) {
      if (id === 0) {
        return this.list
      } else {
        return this.getChild(this.list, id)
      }
    },
    getChild(child, id) {
      for (const i in child) {
        if (child[i].id === id) {
          return child[i]
        } else {
          const result = this.getChild(child[i].children || [], id)
          if (result) {
            return result
          }
        }
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        path: '',
        pid: '0',
        type: 1,
        sort: 0,
        status: 0,
        menuid: '',
        metaTitle: '',
        rval: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getTreeMenuList()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          getsave(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getTreeMenuList()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          getupdate(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      getdelByIdentify(row).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
